<template>
  <el-dialog v-model="visible" title="数据核对" width="600px" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" class="progress-dialog">
    <div class="progress-content">
      <!-- 任务基本信息 -->
      <div class="task-info">
        <div class="info-row">
          <span class="label">任务名称：</span>
          <span class="value">{{ taskName }}</span>
        </div>
        <div class="info-row">
          <span class="label">开始时间：</span>
          <span class="value">{{ startTime }}</span>
        </div>
        <div class="info-row">
          <span class="label">当前状态：</span>
          <el-tag :type="statusTagType" size="small">{{ statusText }}</el-tag>
        </div>
        <div v-if="taskState === 5" class="info-row">
          <span class="label">失败原因：</span>
          <span class="value failure-reason">{{ failureReason }}</span>
        </div>
      </div>

      <!-- 进度显示区域 -->
      <div class="progress-section">
        <div class="progress-header">
          <span class="progress-title">核对进度</span>
        </div>
        <el-progress :percentage="progress" :stroke-width="8" :format="progressFormat" class="progress-bar" />
      </div>

      <!-- 文件下载区域 - 仅在进度100%且任务成功完成时显示 -->
      <div v-if="progress === 100 && taskState === 4" class="download-section">
        <div class="download-header">
          <span class="download-title">文件下载</span>
        </div>
        <div class="download-list">
          <div class="download-item">
            <div class="file-info">
              <el-icon class="file-icon"><Document /></el-icon>
              <span class="file-name">核对结果报告.xlsx</span>
            </div>
            <el-button type="primary" size="small" :loading="downloadLoading" @click="downloadFile">
              <el-icon class="mr-1"><Download /></el-icon>
              下载
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <!-- 任务完成时显示关闭按钮 -->
        <el-button v-if="[4, 5, 6].includes(taskState)" type="primary" @click="closeDialog"> 关闭 </el-button>

        <!-- 进度未完成时显示后台运行和停止任务按钮 -->
        <template v-else>
          <el-button type="primary" @click="runInBackground" :disabled="isBackgroundRunning">
            <el-icon class="mr-1"><Hide /></el-icon>
            {{ isBackgroundRunning ? '已后台运行' : '后台运行' }}
          </el-button>
          <el-button type="danger" :loading="isStopLoading" @click="stopTask">
            <el-icon class="mr-1"><VideoPause /></el-icon>
            停止任务
          </el-button>
        </template>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Hide, VideoPause, Document, Download } from '@element-plus/icons-vue'
import http from '@/support/http'

interface Props {
  modelValue: boolean
  taskId: number | null
  taskName: string
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'task-stopped'): void
  (e: 'close'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 弹窗显示状态
const visible = computed({
  get: () => props.modelValue,
  set: value => emit('update:modelValue', value)
})

// 进度数据
const progress = ref(0)
const processedCount = ref(0)
const totalCount = ref(1000)
const startTime = ref('')
const isBackgroundRunning = ref(false)
const taskStartTime = ref<Date | null>(null)
const taskState = ref(1) // 1=待核对 2=核对排队中 3=核对中 4=核对完成 5=核对失败 6=停止核对
const taskStateName = ref('待核对')
const downloadUrl = ref('')
const failureReason = ref('')
const isStopLoading = ref(false)

// 文件下载数据
interface DownloadFile {
  id: number
  name: string
  size: string
  url: string
}

const statusText = computed(() => {
  return taskStateName.value
})

const statusTagType = computed(() => {
  switch (taskState.value) {
    case 4:
      return 'success' // 核对完成
    case 5:
      return 'danger' // 核对失败
    case 6:
      return 'warning' // 停止核对
    case 3:
      return 'primary' // 核对中
    case 2:
      return 'info' // 核对排队中
    default:
      return 'info' // 待核对
  }
})

// 自定义进度显示格式 - 始终显示百分比，包括100%时也显示100%
const progressFormat = (percentage: number) => {
  return `${percentage}%`
}

// 进度轮询
let progressTimer: NodeJS.Timeout | null = null

const startProgress = async () => {
  if (progressTimer) return

  taskStartTime.value = new Date()
  startTime.value = taskStartTime.value.toLocaleString()

  // 立即获取一次进度
  await fetchProgress()

  // 开始轮询
  progressTimer = setInterval(async () => {
    await fetchProgress()
  }, 2000)
}

const fetchProgress = async () => {
  if (!props.taskId) return

  try {
    const response = await http.get('/dc/check/process', {
      task_id: props.taskId
    })

    if (response.data.code === 10000) {
      const data = response.data.data
      taskState.value = data.task_state
      taskStateName.value = data.task_state_name
      progress.value = data.process
      failureReason.value = data.failure_reason || ''

      // 如果任务完成、失败或停止，停止轮询
      if ([4, 5, 6].includes(data.task_state)) {
        stopProgressTimer()
      }
    }
  } catch (error) {
    console.error('获取进度失败:', error)
  }
}

const stopProgressTimer = () => {
  if (progressTimer) {
    clearInterval(progressTimer)
    progressTimer = null
  }
}

// 后台运行
const runInBackground = () => {
  isBackgroundRunning.value = true
  closeDialog()
  ElMessage.success('任务已切换到后台运行')
}

// 停止任务
const stopTask = async () => {
  try {
    isStopLoading.value = true
    const response = await http.post('/dc/check/stop', {
      task_id: props.taskId
    })

    if (response.data.code === 10000) {
      stopProgressTimer()
      ElMessage.warning('任务已停止')
      emit('task-stopped')
      visible.value = false
    } else {
      ElMessage.error(response.data.message || '停止核对任务失败')
    }
  } catch (error) {
    console.error('停止核对任务失败:', error)
    ElMessage.error('停止核对任务失败，请稍后重试')
  } finally {
    isStopLoading.value = false
  }
}

// 关闭对话框
const closeDialog = () => {
  stopProgressTimer()
  visible.value = false
  emit('close')
}
const downloadLoading = ref(false)
// 下载文件
const downloadFile = async () => {
  try {
    downloadLoading.value = true
    const response = await http.post('/dc/download/execute', {
      task_id: props.taskId
    })
    if (response.data.code === 10000) {
      window.open(response.data.data.file_download_url, '_blank')
    } else {
      ElMessage.error(response.data.message || '下载文件失败')
    }
  } catch (error) {
    console.error('下载文件失败:', error)
  } finally {
    downloadLoading.value = false
  }
}

// 监听弹窗打开，开始进度轮询
watch(visible, async newVal => {
  if (newVal && props.taskId) {
    // 重置状态
    progress.value = 0
    processedCount.value = 0
    isBackgroundRunning.value = false
    taskStartTime.value = null
    taskState.value = 1
    taskStateName.value = '待核对'
    downloadUrl.value = ''
    failureReason.value = ''

    // 开始进度轮询
    setTimeout(async () => {
      await startProgress()
    }, 800)
  } else {
    stopProgressTimer()
  }
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopProgressTimer()
})
</script>

<style scoped>
.progress-content {
  padding: 0;
}

/* 任务信息区域 */
.task-info {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
}

.value {
  color: #303133;
}

.failure-reason {
  color: #f56c6c;
  font-weight: 500;
}

/* 进度区域 */
.progress-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.progress-title {
  font-weight: 500;
  color: #303133;
}

.progress-percent {
  font-weight: 600;
  color: #409eff;
  font-size: 16px;
}

.progress-bar {
  margin-bottom: 8px;
}

.progress-stats {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

/* 文件下载区域 */
.download-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 6px;
}

.download-header {
  margin-bottom: 12px;
}

.download-title {
  font-weight: 500;
  color: #0369a1;
  font-size: 14px;
}

.download-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.download-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #ffffff;
  border: 1px solid #e0f2fe;
  border-radius: 4px;
  transition: all 0.2s;
}

.download-item:hover {
  border-color: #0ea5e9;
  box-shadow: 0 2px 4px rgba(14, 165, 233, 0.1);
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.file-icon {
  color: #0ea5e9;
  font-size: 16px;
}

.file-name {
  font-weight: 500;
  color: #1e293b;
  font-size: 13px;
}

.file-size {
  color: #64748b;
  font-size: 12px;
  margin-left: auto;
  margin-right: 12px;
}

/* 底部按钮区域 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .progress-stats {
    flex-direction: column;
    gap: 4px;
  }

  .dialog-footer {
    flex-direction: column;
  }
}
</style>
